from sanic import Sanic
from sanic.response import text
from sanic.response import json
import time, asyncio

app = Sanic("My Hello, world app")


async def async_express(word):
    '''异步请求'''
    await asyncio.sleep(3)
    print(word)


def sync_express(word):
    '''同步请求'''
    time.sleep(3)
    print(word)


@app.get("/")
async def hello_world(request):
    sync_express("1")
    sync_express("2")
    return text("Hello, world.")


@app.get("/user")
async def create_user(request):
    '''用户请求'''
    start_time = time.time()
    print(request.method, "正在访问", request.path)
    task1 = asyncio.create_task(async_express("发送短信：欢迎先生"))
    task2 = asyncio.create_task(async_express("发送邮箱：你的个人信息是。。。。"))

    await task1
    await task2

    reponse = {
        'code': 200,
        'message': 'sanic server',
        'timestamp': str(time.time() - start_time)
    }

    return json(reponse)


app.run(host="localhost", port=5000)
